<template>
  <div id="app">
    <router-view></router-view>
    <el-dialog
      title="更新提醒"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <span>当前版本为V{{ currentVersion }},需要更新至最高版本！</span>
      <div class="progressStyle">
        <el-progress
          :percentage="ProgressValue"
          v-if="showProgress"
        ></el-progress>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">暂不更新</el-button>
        <el-button type="primary" @click="downloadFile">立即更新</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import updataCard from "../renderer/pages/HomePage/components/updataCard";
import config from '../package.json';
import semver from 'semver';
import axios from 'axios';
import request from 'request';
import Utils from '@/libs/Utils.js';
// const execFile = require("child_process").exec;
import fs from 'fs';
export default {
  name: 'app',
  // components: { updataCard },
  data() {
    return {
      updataShow: false,
      upDataList: [], // 更新信息
      centerDialogVisible: false,
      currentVersion: '', // 当前版本
      donwloadUrl: '', // 下载更新地址
      showProgress: false, // 是否展示进度条
      ProgressValue: 0, // 进度条值
      packageURL: 'D:PPM.exe' // 更新包地址
    };
  },
  mounted() {
    // Utils.connectWebSocket('ws://192.168.75.142:9898/ws');
    // this.initWebSocket()
    window.addEventListener('beforeunload', (e) => this.listenPage(e));
    // this.listenPage();
    const platform = navigator.userAgent;
    if (platform.indexOf('Electron') != -1) {
      this.checkLineVersion('app');
      // this.isTipShowFun()
    } else {
      // this.checkLineVersion("web");
      // this.isTipShowFun()
    }
    // this.execFileFc();
    //  console.log('changeTableHeight',window.innerHeight)
    //  this.$store.dispatch("changeTableHeight",window.innerHeight)
    window.addEventListener(
      'resize',
      () => {
        return (() => {
          this.$store.dispatch('changeTableHeight', window.innerHeight);
        })();
      },
      false
    );
  },
  computed: {
    currentName() {
      return this.$store.state.app.currentPagePath;
    }
  },
  methods: {
    // 监听页面刷新情况，保留当前路由的页面，其他的页面全部删除掉
    listenPage(e) {
      var currentPath = this.$route.path;
      var tagList = JSON.parse(window.sessionStorage.getItem('TagList'));
      var currentTag = tagList.filter((item) => item.path == currentPath);
      window.sessionStorage.setItem('TagList', JSON.stringify(currentTag));
    },
    // 关闭更新提示
    uClose() {
      this.updataShow = false;
      this.$http
        .post(
          `/${this.$ServiceName}/api/external/readlog/${this.$version}/insert`
        )
        .then((res) => {});
    },
    execFileFc() {
      const child = execFile(this.packageURL, (error, stdout, stderr) => {
        if (error) {
          throw error;
        }
        console.log(stdout);
      });
    },
    // 版本对比,进行版本更新
    async checkLineVersion(platform) {
      var _this = this;
      let version = '';
      const res = await _this.$http.get(
        `/${this.$ServiceName}/api/external/checkupdate/getversion`
      );
      // console.log(1111,res)
      console.log(res);
      version = res.data.data.version; // 获取版本赋值
      _this.donwloadUrl = res.data.data.packageUrl; // 获取下载更新包下载地址
      _this.upDataList.push(res.data.data.remark ? res.data.data.remark : ''); // 更新信息
      // version = config.version;
      _this.currentVersion = config.version;
      // 进行package.json中版本和线上版本比较
      try {
        if (semver.lt(config.version, version)) {
          if (platform == 'app') {
            _this.centerDialogVisible = true;
          }
          //  else {
          //   //web端
          //   //判断是否已经提示过了更新
          //   let isTipUpdata = localStorage.getItem("isTipUpdata");
          //   if (!isTipUpdata) {
          //     this.updataShow = true;
          //     localStorage.setItem("isTipUpdata", true);
          //     //记录当前版本
          //     localStorage.setItem("version", _this.currentVersion);
          //   } else {
          //     // 与本地储存的版本比较
          //     if (_this.currentVersion != localStorage.getItem("version")) {
          //       this.updataShow = true;
          //     }
          //   }
          // }
        }
      } catch (err) {
        console(err);
      }
    },
    // 是否弹出更新
    isTipShowFun() {
      this.$http
        .get(
          `/${this.$ServiceName}/api/external/readlog/${this.$version}/selectbyaccno`
        )
        .then((res) => {
          console.log(res);
          if (res.data.success) {
            if (!res.data.data) {
              this.getWebMessage();
            }
          }
        });
    },
    // 获取web端更新信息
    getWebMessage() {
      const _this = this;
      this.$http
        .get(`/${this.$ServiceName}/api/external/versioncontrol/selectremark`)
        .then((res) => {
          console.log(res);
          if (res.data.success) {
            this.updataShow = true;
            if (res.data.data) {
              _this.upDataList = res.data.data.split('///').slice(0, -1);
              console.log(_this.upDataList);
            }
          }
        });
    },
    // 模拟下载更新包
    downloadFile() {
      // this.centerDialogVisible = false;//隐藏更新入口
      this.showProgress = true; // 展示进度条
      var _this = this;
      _this.downloadFileDetail(_this.donwloadUrl, _this.packageURL);
      // var fd = fs.openSync('/Users/gaofeng/Documents/vueWorkspace/psys-front-master/src/renderer/update/SHASUMS256.txt', 'r+');
      // alert(fd);
      // fs.stat('/Users/gaofeng/Documents/vueWorkspace/psys-front-master/src/renderer/update/SHASUMS256.txt', function (err, stats) {
      //     console.log(stats);//true
      // })
    },
    // 下载更新文件 参数一下载路径，参数二保存路径
    downloadFileDetail(file_url, targetPath) {
      var _this = this;
      // Save variable to know progress
      var received_bytes = 0;
      var total_bytes = 0;

      var req = request({
        method: 'GET',
        uri: file_url
      });
      var out = fs.createWriteStream(targetPath);
      req.pipe(out);
      req.on('response', function(data) {
        // Change the total bytes value to get progress later.
        total_bytes = parseInt(data.headers['content-length']);
      });
      req.on('data', function(chunk) {
        // Update the received bytes
        received_bytes += chunk.length;
        _this.showProgressF(received_bytes, total_bytes);
      });
      req.on('end', function() {
        // alert("更新成功！");
        _this.$message.success('更新成功！');
        _this.centerDialogVisible = false; // 隐藏更新入口
        // 打开文件
        _this.execFileFc();
      });
    },
    // 展示进度条
    showProgressF(received, total) {
      console.log(received);
      console.log(total);
      var percentage = (received * 100) / total;
      this.ProgressValue = Number(percentage.toFixed(1));
    }
  }
};
</script>

<style>
/* 把所有表格的字都设为不可选取 */
/* .el-table--scrollable-x {
  -moz-user-select: none;
  -webkit-user-select: none;
  user-select: none;
} */
.upDW {
  transform: translateX(-175px);
}
#app {
  height: 100vh;
}
.el-tooltip__popper {
  font-size: 14px;
  max-width: 300px;
  background: #ffffff;
  color: #0e0e0f;
  border: 1px solid #e1e4eb !important;
}
.tip-style{
  background: #195794 !important;
  color: #e1e4eb !important;
}
.progressStyle {
  margin-bottom: -15px;
  margin-top: 15px;
}
.el-tooltip__popper.attch_list {
  font-size: 14px;
  background: #ffff !important;
  color: #303133 !important;
  max-width: 300px;
  border: 1px solid #e1e4eb;
}
.el-tooltip__popper[x-placement^='top'] .popper__arrow:after {
  border-top-color: #f5f7fa !important;
}
.attch_list.el-tooltip__popper[x-placement^='top'] .popper__arrow:after {
  border-top-color: #fff !important;
}
.attch_list.el-tooltip__popper[x-placement^='bottom'] .popper__arrow:after {
  border-bottom-color: #fff !important;
}
.attch_list.el-tooltip__popper[x-placement^='bottom'] .popper__arrow {
  border-bottom-color: #e1e4eb !important;
}
.el-tooltip__popper[x-placement^='top'] .popper__arrow {
  border-top-color: #e1e4eb !important;
}

/* 全局配置 */
* {
  padding: 0;
  margin: 0;
  font-family: Arial, 'Microsoft YaHei', 微软雅黑, 'MicrosoftJhengHei', 华文细黑,
    STHeiti, MingLiu;
}
.el-pagination {
  font-weight: 100 !important;
}
.home-container {
  overflow: hidden;
}
/* .el-table__body{
      margin-bottom: 0.5rem;
} */
*::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px !important; /*高宽分别对应横竖滚动条的尺寸*/
  height: 10px !important;
}
*::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px !important;
  background-color: #ddd;
  /* background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
  ); */
}
*::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #fff;
  border-radius: 10px;
  border-top: 1px solid #e1e4eb;
}

.scrollbar-wrapper {
  overflow-x: hidden !important;
}
/* table全局样式 */
.el-table td,
.el-table th {
  padding: 0 !important;
}
.el-table .cell {
  line-height: 40px !important;
}
.el-table th > .cell {
  line-height: 40px !important;
}
.el-table tr.hover-row > td {
  border-top: 1px solid transparent;
  border-bottom: 1px solid transparent;
  border-bottom-color: #a4bff5 !important;
  border-top-color: #a4bff5 !important;
  background: transparent !important;
  color: #303133 !important;
}
/* table全局样式 */
.el-table__body tr.current-row > td:first-of-type {
  border-left: 1px solid;
  border-left-color: #338ce8 !important;
}
.el-table__body tr.current-row > td:last-child {
  border-right: 1px solid;
  border-right-color: #338ce8 !important;
}
.el-table__body tr.current-row > td {
  border-top: 1px solid transparent;
  border-bottom: 1px solid transparent;
  border-bottom-color: #338ce8 !important;
  border-top-color: #338ce8 !important;
  background: transparent !important;
  color: #303133 !important;
}
/* .el-table__body tr.current-row:nth-child(even) {
  background: #f5f7fa !important;
} */
.pcs-class div {
  color: #00bb91;
}
.weight-class div {
  color: #ff8c3f;
}
.el-form-item--mini.el-form-item {
  margin-bottom: 0 !important;
}

.el-table__fixed,
.el-table__fixed-right {
  height: 100% !important;
  min-height: 100% !important;
}
/* 全局修改table里面的按钮颜色 */
.el-table .el-button--mini {
  color: #606266 !important;
}
/* 抽屉header选中 */
:focus {
  outline: 0;
}

/* 去掉抽屉的关闭按钮 */
.el-drawer__header .el-icon-close:before {
  content: '' !important;
}
/* 表格滑动 */
.el-table__body {
  overflow-y: auto;
}
.el-textarea__inner {
  height: 100px !important;
}
.el-textarea {
  vertical-align: bottom;
}
.el-popper[x-placement^='bottom'] {
  margin-top: 0px !important;
}
/* 抽屉的底部样式 */
.demo-drawer__footer {
  text-align: right;
  padding-right: 1rem;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}

.box .v-modal {
  z-index: 200 !important;
  display: none !important;
  width: 50% !important;
}
[v-cloak] {
  display: none;
}
.el-submenu__title{
  height: 40px !important;
  line-height: 40px !important;
}
.el-submenu__title:hover{
  background-color: #000 !important;
}
</style>
